package com.lagou.rpcserver.lagou.handler;

import com.lagou.pojo.RpcRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
@Component
@ChannelHandler.Sharable
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements BeanFactoryAware {

	private BeanFactory beanFactory;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		final RpcRequest rpcRequest;
		if (!(msg instanceof RpcRequest)) {
			System.out.println("未获取到RpcRequest");
			return;
		}
		rpcRequest = (RpcRequest) msg;
		System.out.println("获取到RpcRequest：" + rpcRequest);

		final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		final Class<?> aClass = classLoader.loadClass(rpcRequest.getClassName());
		final Object bean = beanFactory.getBean(aClass);
		final Method method = aClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
		final Object invoke = method.invoke(bean, rpcRequest.getParameters());
		rpcRequest.setResult((String) invoke);

		System.out.printf("%s方法调用成功，返回值为[%s]", rpcRequest.getMethodName(), rpcRequest);
		ctx.writeAndFlush(rpcRequest);
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	public BeanFactory getBeanFactory() {
		return beanFactory;
	}
}
